package com.aps.common.controller;

import com.aps.common.entity.ApsCode;
import com.aps.common.entity.Result;
import com.aps.common.service.ApsCodeService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * APS 码值管理控制器
 * 提供码值相关的REST API接口
 * 
 * @author nbZhuozh
 * @since 2025-11-21
 */
@Slf4j
@RestController
@RequestMapping("/api/aps-code")
@Tag(name = "码值管理", description = "APS 码值管理相关的API接口")
public class ApsCodeController {

    @Resource
    private ApsCodeService apsCodeService;

    /**
     * 分页查询当前租户下所有码值
     *
     * @param pageNum  页码，默认1
     * @param pageSize 每页大小，默认10
     * @return 分页结果
     */
    @GetMapping("/page")
    @Operation(summary = "分页查询码值", description = "分页查询当前租户下所有码值")
    public Result<Page<ApsCode>> selectPage(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") int pageNum,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") int pageSize) {
        try {
            Page<ApsCode> page = apsCodeService.selectPageByTenantId(pageNum, pageSize);
            return Result.success(page, "查询成功");
        } catch (Exception e) {
            log.error("分页查询码值失败", e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    /**
     * 查询当前租户下所有码值（不分页）
     *
     * @return 所有码值列表
     */
    @GetMapping("/list")
    @Operation(summary = "查询所有码值", description = "查询当前租户下所有码值（不分页，从缓存读取）")
    public Result<List<ApsCode>> selectAll() {
        try {
            List<ApsCode> list = apsCodeService.selectAllByTenantId();
            return Result.success(list, "查询成功");
        } catch (Exception e) {
            log.error("查询所有码值失败", e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据码表类型查询码值列表
     *
     * @param codeType 码表类型（如：USER_STATUS、ORDER_TYPE）
     * @return 指定类型的码值列表
     */
    @GetMapping("/type/{codeType}")
    @Operation(summary = "按类型查询码值", description = "根据码表类型查询当前租户下的码值列表")
    public Result<List<ApsCode>> selectByCodeType(
            @Parameter(description = "码表类型", required = true) @PathVariable String codeType) {
        try {
            if (StringUtils.isBlank(codeType)) {
                return Result.error(400, "码表类型不能为空");
            }
            List<ApsCode> list = apsCodeService.selectByCodeType(codeType);
            return Result.success(list, "查询成功");
        } catch (Exception e) {
            log.error("按类型查询码值失败：codeType={}", codeType, e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID查询码值
     *
     * @param id 码值ID
     * @return 码值对象
     */
    @GetMapping("/{id}")
    @Operation(summary = "查询码值详情", description = "根据ID查询码值详情")
    public Result<ApsCode> selectById(
            @Parameter(description = "码值ID", required = true) @PathVariable String id) {
        try {
            if (StringUtils.isBlank(id)) {
                return Result.error(400, "ID不能为空");
            }
            ApsCode apsCode = apsCodeService.selectById(id);
            if (apsCode == null) {
                return Result.error(404, "未找到指定的码值");
            }
            return Result.success(apsCode, "查询成功");
        } catch (Exception e) {
            log.error("查询码值详情失败：id={}", id, e);
            return Result.error(500, "查询失败: " + e.getMessage());
        }
    }

    /**
     * 新增码值
     *
     * @param apsCode 码值对象
     * @return 操作结果
     */
    @PostMapping("/create")
    @Operation(summary = "新增码值", description = "新增一个码值记录")
    public Result<String> insert(@RequestBody ApsCode apsCode) {
        try {
            // 参数校验
            if (apsCode == null) {
                return Result.error(400, "参数不能为空");
            }
            if (StringUtils.isBlank(apsCode.getCodeType())) {
                return Result.error(400, "码表类型不能为空");
            }
            if (StringUtils.isBlank(apsCode.getCodeValue())) {
                return Result.error(400, "码值不能为空");
            }

            boolean success = apsCodeService.insert(apsCode);
            if (success) {
                return Result.success(apsCode.getId(), "新增成功");
            } else {
                return Result.error(400, "新增失败，可能存在重复的码值");
            }
        } catch (Exception e) {
            log.error("新增码值失败", e);
            return Result.error(500, "新增失败: " + e.getMessage());
        }
    }

    /**
     * 修改码值
     *
     * @param apsCode 码值对象（必须包含ID）
     * @return 操作结果
     */
    @PostMapping("/modify")
    @Operation(summary = "修改码值", description = "修改一个码值记录")
    public Result<String> update(@RequestBody ApsCode apsCode) {
        try {
            // 参数校验
            if (apsCode == null || StringUtils.isBlank(apsCode.getId())) {
                return Result.error(400, "参数错误或ID为空");
            }

            boolean success = apsCodeService.update(apsCode);
            if (success) {
                return Result.success("修改成功");
            } else {
                return Result.error(400, "修改失败，可能记录不存在或存在重复的码值");
            }
        } catch (Exception e) {
            log.error("修改码值失败：id={}", apsCode != null ? apsCode.getId() : null, e);
            return Result.error(500, "修改失败: " + e.getMessage());
        }
    }

    /**
     * 删除码值
     *
     * @param id 码值ID
     * @return 操作结果
     */
    @GetMapping("/del/{id}")
    @Operation(summary = "删除码值", description = "根据ID删除码值（逻辑删除）")
    public Result<String> delete(
            @Parameter(description = "码值ID", required = true) @PathVariable String id) {
        try {
            if (StringUtils.isBlank(id)) {
                return Result.error(400, "ID不能为空");
            }

            boolean success = apsCodeService.delete(id);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error(400, "删除失败，可能记录不存在或为系统内置码值");
            }
        } catch (Exception e) {
            log.error("删除码值失败：id={}", id, e);
            return Result.error(500, "删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除码值
     *
     * @param ids 码值ID列表
     * @return 操作结果
     */
    @PostMapping("/batch-delete")
    @Operation(summary = "批量删除码值", description = "批量删除码值（逻辑删除）")
    public Result<String> batchDelete(@RequestBody List<String> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.error(400, "ID列表不能为空");
            }

            boolean success = apsCodeService.batchDelete(ids);
            if (success) {
                return Result.success("批量删除成功");
            } else {
                return Result.error(400, "批量删除失败，可能包含系统内置码值或记录不存在");
            }
        } catch (Exception e) {
            log.error("批量删除码值失败", e);
            return Result.error(500, "批量删除失败: " + e.getMessage());
        }
    }

    /**
     * 清除当前租户的所有缓存
     *
     * @return 操作结果
     */
    @PostMapping("/clear-cache")
    @Operation(summary = "清除缓存", description = "清除当前租户的所有码值缓存")
    public Result<String> clearCache() {
        try {
            apsCodeService.clearAllCache();
            return Result.success("缓存清除成功");
        } catch (Exception e) {
            log.error("清除缓存失败", e);
            return Result.error(500, "清除缓存失败: " + e.getMessage());
        }
    }
}

